//
//  PYHttp.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "PYHttp.h"

#define needLog YES

@implementation PYHttp

+ (AFHTTPSessionManager *)manager
{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
    });
    return manager;
}

/**
 IHomeServer的网络请求
 
 @param URLString 接口地址
 @param parameters 参数
 @param requestType 请求类型
 @param success 请求成功的回调
 @param failure 请求失败的回调
 */
+ (void)requestIHomeServerWithURLString:(NSString *)URLString
                             parameters:(nullable id)parameters
                            requestType:(PYRequestType)requestType
                                success:(nullable void (^)(id _Nullable))success
                                failure:(nullable void (^)(NSString * _Nullable))failure
{
    [self requestWithURLString:URLString parameters:parameters requestType:requestType bodyType:PY_JSON success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSInteger code = [responseObject integerValueForKey:@"code" default:0];
        id data = [responseObject objectForKey:@"data"];
        NSString *message = [responseObject stringValueForKey:@"message" default:nil];
        if (code == 200) {
            if (success) {
                success(data);
            }
        } else {
            if (message) {
                NSLog(@"请求失败，message = %@", message);
            }
            if (failure) {
                failure(message);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.localizedDescription);
        }
    }];
}

/**
 * 通用网络请求
 */
+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
                 requestType:(PYRequestType)requestType
                    bodyType:(PYBodyType)bodyType
                     success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nonnull))success
                     failure:(nullable void (^)(NSURLSessionDataTask * _Nonnull, NSError * _Nonnull))failure
{
    PYHttp *httpRequest = [[PYHttp alloc] init];
    
    if (URLString.length == 0) {
        NSLog(@"URL为空");
        return;
    }
    if (needLog) {
        NSLog(@"\n AF网络请求参数列表:%@\n\n 接口名: %@\n\n", [parameters isKindOfClass:[NSDictionary class]] ? parameters : parameters, URLString);
    }
    
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [PYHttp manager];
    if (bodyType == PY_JSON) {
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    } else if (bodyType == PY_Form_Data) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    // 2.申明返回的结果是JSON类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    // 3.如果接受类型不一致请替换
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                         @"application/json",
                                                         //                                                         @"text/json",
                                                         //                                                         @"text/javascript",
                                                         //                                                         @"text/html",
                                                         @"text/plain",
                                                         //                                                         @"text/xml",
                                                         nil];
    
    // 4.请求超时，时间设置
    manager.requestSerializer.timeoutInterval = 30;
    // 5.选择请求方式 GET 或 POST 或 DELETE 或 PUT
    switch (requestType) {
        case PY_GET:
        {
            [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                [httpRequest p_successWithTask:task responseObject:responseObject URLString:URLString success:success];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [httpRequest p_failureWithTask:task error:error failure:failure];
            }];
        }
            break;
            
        case PY_POST:
        {
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                [httpRequest p_successWithTask:task responseObject:responseObject URLString:URLString success:success];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [httpRequest p_failureWithTask:task error:error failure:failure];
            }];
        }
            break;
            
        case PY_DELETE:
        {
            [manager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [httpRequest p_successWithTask:task responseObject:responseObject URLString:URLString success:success];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [httpRequest p_failureWithTask:task error:error failure:failure];
            }];
        }
            break;
            
        case PY_PUT:
        {
            [manager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [httpRequest p_successWithTask:task responseObject:responseObject URLString:URLString success:success];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [httpRequest p_failureWithTask:task error:error failure:failure];
            }];
        }
            break;
        default:
            break;
    }
}

- (void)p_successWithTask:(NSURLSessionDataTask *)task
           responseObject:(id)responseObject
                URLString:(NSString *)URLString
                  success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
{
    if (needLog) {
        NSLog(@"%@_responseObject = %@", URLString, responseObject);
    }
    if (success) {
        success(task, responseObject);
        // 这里设置为nil没什么卵用
        //        success = nil;
    }
}

- (void)p_failureWithTask:(NSURLSessionDataTask *)task
                    error:(NSError *)error
                  failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    NSLog(@"\n 请求失败:%@\n\n",error);
    NSString *errorDesc = [error.userInfo objectForKey:@"NSLocalizedDescription"];
    NSLog(@"errorDesc = %@", errorDesc);
    if (errorDesc.length) {
//        [MBProgressHUD py_showText:errorDesc];
    }
    if (failure) {
        if (error.code != -999) {
            failure(task, error);
        }
        // 这里设置为nil没什么卵用
        //        failure = nil;
    }
}

+ (void)uploadData:(NSData *)data
          progress:(nullable void (^)(float))progress
        completion:(nonnull void (^)(NSString * _Nullable))completion
{
    NSString *url = [NSString stringWithFormat:@"%@/%@/2", ip_address, getUploadFileTokenURL];
    [PYHttp requestWithURLString:url parameters:nil requestType:PY_GET bodyType:PY_JSON success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSString *token = responseObject[@"data"];
        //        NSString *key = responseObject[@"key"];
        NSString *key = [NSString stringWithFormat:@"iOS_%ld_%d", (long)([[NSDate date] timeIntervalSince1970] * 1000), arc4random() % 1000];
        //        NSLog(@"key = %@", key);
        if (token && key) {
            QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                //                NSLog(@"upload progress = %f", percent);
                if (progress) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        progress(percent);
                    });
                }
            }];
            QNUploadManager *manager = [QNUploadManager new];
            [manager putData:data key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                //                NSLog(@"info = %@", info);
                //                NSLog(@"resp = %@", resp);
                NSString *originalKey = [resp objectForKey:@"key"];
                if (completion) {
                    if (originalKey) {
                        completion([NSString stringWithFormat:@"%@/%@", qiniu_ip_address, originalKey]);
                    } else {
                        NSLog(@"上传数据到七牛，上传失败");
                        completion(nil);
                    }
                }
            } option:option];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (completion) {
            NSLog(@"获取上传token失败:%@", error);
            completion(nil);
        }
    }];
}

/// 下载文件
/// @param urlStr 文件url
/// @param path 文件保存的路径
/// @param progress 下载进度
/// @param completion 下载结果
+ (void)downloadFileWithUrl:(NSString *)urlStr
                       path:(NSString *)path
                   progress:(nullable void(^)(float percent))progress
                 completion:(void(^)(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error))completion;
{
    /* 创建网络下载对象 */
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    /* 下载地址 */
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [manager setDownloadTaskDidFinishDownloadingBlock:^NSURL * _Nullable(NSURLSession * _Nonnull session, NSURLSessionDownloadTask * _Nonnull downloadTask, NSURL * _Nonnull location) {
        /* 设定下载到的位置 */
          return [NSURL fileURLWithPath:path];
    }];
    /* 开始请求下载 */
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
        dispatch_async_on_main_queue(^{
            if (progress) {
                progress(downloadProgress.fractionCompleted);
            }
        });

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //如果需要进行UI操作，需要获取主线程进行操作
        });
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:path];
                
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        dispatch_async_on_main_queue(^{
            if (completion) {
                completion(response, filePath, error);
            }
        });
    }];
     [downloadTask resume];
}
@end
